package com.kedacom.ctsp.authority.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.kedacom.ctsp.authority.dto.DataAccessDTO;
import com.kedacom.ctsp.authority.dto.FieldDTO;
import com.kedacom.ctsp.authority.entity.Resource;
import com.kedacom.ctsp.authority.util.AuthorityTreeUtil;
import com.kedacom.ctsp.lang.StringUtil;
import com.kedacom.ctsp.lang.mapper.BeanMapper;
import com.kedacom.ctsp.lang.mapper.BeanMapperException;
import com.kedacom.ctsp.lang.mapper.CollComponentType;
import com.kedacom.ctsp.web.vo.AbstractTreeSortSupportVO;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.IllegalFormatException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资源实体类
 *
 * @author sunchenjie
 */
@Data
@ApiModel("资源实体")
@Slf4j
public class SimpleResourceVO extends AbstractTreeSortSupportVO<Resource, ResourceVO, String> implements ResourceVO {

    /**
     * 主键id
     */
    private String id;
    /**
     * 名称
     */
    private String name;
    /**
     * 标识
     */
    private String sign;
    /**
     * 类型 （菜单、按钮等）
     */
    private String type;
    /**
     * 描述
     */
    private String description;
    /**
     * 数据
     */
    private String data;
    /**
     * url
     */
    private String url;

    private Boolean checked;
    /**
     * 扩展字段
     */
    private String extendedField;
    /**
     * 可选字段
     */
    @CollComponentType(FieldDTO.class)
    private List<FieldDTO> field;
    /**
     * 数据访问条件
     */
    @CollComponentType(DataAccessDTO.class)
    private List<DataAccessDTO> dataAccess;
    /**
     * 数据访问范围
     */
    private String dataScope;

    @Transient
    private List<SimpleResourceSettingRelationVO> details;
    /**
     * 客户端标识
     */
    private String clientSign;
    private RequestMethod method;

    @Override
    public Resource convertTo(Resource entity) throws BeanMapperException {
        log.info("对象资源转换,把vo转换成entity");

        super.convertTo(entity);

        List<DataAccessDTO> dataAccess = this.getDataAccess();
        List<FieldDTO> field = this.getField();
        String dataScope = this.getDataScope();

        /**
         * json 字符串转换为对象
         */
        if (CollectionUtils.isNotEmpty(dataAccess)) {
            entity.setDataAccess(JSONObject.toJSONString(dataAccess));
        }
        if (CollectionUtils.isNotEmpty(field)) {
            entity.setField(JSONObject.toJSONString(field));
        }
        //转换children
        if (CollectionUtils.isNotEmpty(this.getChildren())) {
            List<ResourceVO> children = this.getChildren();
            List<Resource> collect = children.stream().map(
                    c -> {
                        Resource childEntity = c.convertTo(BeanMapper.newInstanceSilently(Resource.class));
                        return childEntity;
                    }
            ).collect(Collectors.toList());
            entity.setChildren(collect);
        }
        AuthorityTreeUtil.addParent(entity, this);

        return entity;
    }

    @Override
    public ResourceVO convertFrom(Resource entity) throws IllegalFormatException {
        ResourceVO vo = super.convertFrom(entity);
        if (entity != null) {
            String dataScope = entity.getDataScope();
            if (!StringUtil.isNullOrEmpty(dataScope)) {
                vo.setDataScope(dataScope);
            }
            String dataAccess = entity.getDataAccess();
            if (!StringUtil.isNullOrEmpty(dataAccess)) {
                try {
                    ArrayList<DataAccessDTO> dataAccessDTO = JSON.parseObject(dataAccess, new TypeReference<ArrayList<DataAccessDTO>>() {
                    });
                    vo.setDataAccess(dataAccessDTO);
                } catch (JSONException e) {
                    log.error("dataAccess 转换错误:[{}],[{}]", entity.getId(), e.getMessage());
                    vo.setDataAccess(null);
                }
            }

            String field = entity.getField();
            if (!StringUtil.isNullOrEmpty(field)) {
                try {
                    ArrayList<FieldDTO> fieldDTO = JSON.parseObject(field, new TypeReference<ArrayList<FieldDTO>>() {
                    });
                    vo.setField(fieldDTO);
                } catch (JSONException e) {
                    log.error("field 转换错误:[{}],[{}]", entity.getId(), e.getMessage());
                    vo.setField(null);
                }
            }
        }
        return vo;
    }

}
